package com.wlsk.license.handler;

import com.wlsk.license.common.exception.BusinessException;
import com.wlsk.license.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理 @Valid和 @Validated注解参数校验失败异常
     */
    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    public Result exceptionHandler(HttpServletRequest request, Exception e) {
        log.error("【统一异常拦截】请求地址：{}, 错误信息:", request.getRequestURI(), e);
        // 注解验证抛出的异常
        if (e instanceof MethodArgumentNotValidException) {
            // 获取错误信息
            String error = Objects.requireNonNull(((MethodArgumentNotValidException) e).getBindingResult().getFieldError()).getDefaultMessage();
            return Result.failed(error);
        } else if (e instanceof BusinessException) {
            return Result.failed(e.getMessage());
        }
        return Result.failed("业务处理异常");
    }
}
